package com.ctyon.watchmanager.ui.fragment;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.PolylineOptions;
import com.ctyon.common.util.DataUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.databinding.FragmentMapHisoryBinding;
import com.ctyon.watchmanager.model.db.entity.LocationEntity;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.MapHistoryPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class MapHistoryFragment extends BaseFragment {

    public static final String TAG = "MapHistoryFragment";

    private FragmentMapHisoryBinding mBinding;
    private AMap aMap;
    private UiSettings mUiSettings;
    private List<LatLng> latLngs = new ArrayList<>();
    private Marker beginMarker, endMarker;

    public static MapHistoryFragment newInstance() {
        final MapHistoryFragment fragment = new MapHistoryFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_map_hisory, container, false);
        mBinding.setMapHistoryPresenter(mapHistoryPresenter);
        mBinding.map.onCreate(savedInstanceState);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (aMap == null) {
            aMap = mBinding.map.getMap();
            mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(true);//控制缩放按钮是否显示
//            mUiSettings.setZoomPosition(1);//设置缩放按钮的位置
            mUiSettings.setScaleControlsEnabled(true);//控制比例尺控件是否显示
        }

        loadData();
    }

    private void loadData() {
        Observable.create((ObservableOnSubscribe<List<LocationEntity>>) emitter -> {
            latLngs.clear();
            List<LocationEntity> locationEntities = BasicApp.getInstance().getRepository().loadLocations();
            String locationE = "";
            if (locationEntities.size() > 0){
                for (LocationEntity locationEntity : locationEntities) {
                    String location = locationEntity.getLocation();
                    if (!DataUtil.isEmptyOr(location) && location.contains("*")) {
                        if (location.equals(locationE)){
                            continue;
                        }
                        locationE = location;
                        String[] s = location.split("\\*");
                        LatLng latLng = new LatLng(Double.valueOf(s[1]), Double.valueOf(s[0]));
                        latLngs.add(latLng);
                    }
                }
                emitter.onNext(locationEntities);
            }
        })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    Logger.t(LTAG).i("latLing count = " + latLngs.size());
                    if (latLngs.size() > 0) {
                        aMap.addPolyline(new PolylineOptions().addAll(latLngs).width(10).color(Color.argb(255, 1, 1, 1)));
                        mapCenter();
                    }
                });
    }

    private final MapHistoryPresenter mapHistoryPresenter = new MapHistoryPresenter() {

    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mBinding.map.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mBinding.map.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mBinding.map.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.map.onSaveInstanceState(outState);
    }

    private void mapCenter() {

        //添加Marker显示定位位置
        LatLng beginLat = latLngs.get(0);
        if (beginMarker == null) {
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(beginLat);
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_map_begin)));
            // 将Marker设置为贴地显示，可以双指下拉地图查看效果
            //如果是空的添加一个新的,icon方法就是设置定位图标，可以自定义
            beginMarker = aMap.addMarker(markerOption);
        } else {
            //已经添加过了，修改位置即可
            beginMarker.setPosition(beginLat);
        }

        LatLng endLat = latLngs.get(latLngs.size()-1);
        if (endMarker == null) {
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(endLat);
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_map_end)));
            // 将Marker设置为贴地显示，可以双指下拉地图查看效果
            //如果是空的添加一个新的,icon方法就是设置定位图标，可以自定义
            endMarker = aMap.addMarker(markerOption);
        } else {
            //已经添加过了，修改位置即可
            endMarker.setPosition(endLat);
        }

        //然后可以移动到定位点,使用animateCamera就有动画效果
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(beginLat, 15));
    }

}
